<?php
/**
 * [LupMisNotAllowedSync]
 * 本代码为系统自动生成代码，请根据自己业务进行修改;
 * 生成时间 2022-02-18 18:16:27;
 * 版权所有 2020-2022 lizhongwen，并保留所有权利;
 * 说明: 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用；不允许对程序代码以任何形式任何目的的再发布;
 * 作者: 中文Lee;
 * 作者主页: http://www.lizhongwen.com;
 * 邮箱: 360811363@qq.com;
 * QQ: 360811363;
 */
namespace modules\sys\service\impl;

use application\core\Result;
use application\core\SnowFlake;
use modules\sys\component\SetCacheComponent;
use modules\sys\mapper\PageMapper;
use modules\sys\mapper\RoleTreeMapper;
use modules\sys\mapper\TreeMapper;
use modules\sys\service\TreeService;

class TreeServiceImpl implements TreeService
{

    public function lists(array $data): array
    {
        $pageRs = PageMapper::lists();
        $pageRs = array_column($pageRs, NULL, 'id');
        if(!empty($data['role_id'])){
            //查询该角色的菜单
            $listsRole = RoleTreeMapper::listsByRoleId(['role_id' => $data['role_id']]);
            $listsRole = array_column($listsRole, NULL, 'tree_id');
        }
        $treeRs = TreeMapper::lists($data);
        foreach ($treeRs as $k => $v) {
            $treeRs[$k]['sys_page'] = $pageRs[$v['page_id']] ?? null;
            if(!empty($data['role_id'])) {
                $treeRs[$k]['checked'] = isset($listsRole[$v['id']]);
            }
        }
        return Result::success(false,$treeRs);
    }

    public function add(array $data): array
    {
        $data['id'] = SnowFlake::instance()->nextId();
        $add = TreeMapper::add($data);
        if($add == 0){
            return Result::fail(false,[],"添加失败");
        }
        SetCacheComponent::tree();
        return Result::success(true,[],"添加成功");
    }
    public function del(array $data): array
    {
        //先查询是否有下级菜单
        $listsByPidRs = TreeMapper::listsByPid(['pid' => $data['ids']]);
        if(!empty($listsByPidRs)){
            return Result::fail(false,[],"请先删除下级菜单！");
        }
        $edit = TreeMapper::del(['id' => $data['ids']]);
        if($edit == 0){
            return Result::fail(false,[],"数据不存在");
        }
        SetCacheComponent::tree();
        return Result::success(true,[],"删除成功");
    }

    public function edit(array $data): array
    {
        $edit = TreeMapper::edit($data);
        if($edit == 0){
            return Result::fail(false,[],"未修改任何数据");
        }
        SetCacheComponent::tree();
        return Result::success(true,[],"修改成功");
    }

    public function query(array $data): array
    {
        return Result::success(false,TreeMapper::query($data));
    }
}

